<template>

  <div>
    <el-container>
      <!-- 头部 -->
      <el-header class="head">
        <div class="logo" @click="goToIndex">
          <h1>睿雅酒店</h1>
        </div>

        <div class="actions">
          <el-button round class="action-btn" style="color:#606266 ;">
            <el-icon style="color: #303133;">
              <Download />
            </el-icon> 下载App
          </el-button>
          <el-button type="text" class="action-btn">
            <el-icon>
              <Phone />
            </el-icon> 联络我们
          </el-button>
          <el-button v-if="!UserLoginToken" type="text" class="action-btn"
          @click="orderLogin()">
            <el-icon>
              <Search />
            </el-icon> 我的订单
          </el-button>
          <el-button v-else type="text" class="action-btn" @click="gotoAllPersonalOrders">
            <el-icon>
              <Search />
            </el-icon> 我的订单
          </el-button>
          <el-button v-if="!UserLoginToken" type="primary" class="login-btn"
            @click="showDialog = true">登录/注册</el-button>
          <div v-else style="display: flex; justify-content: center; align-items: center;">
            <el-dropdown trigger="click" @command="handleDropdownCommand">
              <div style="display: flex; align-items: center; cursor: pointer;">
                <el-avatar style="margin-left: 20px;" src="/pic/ruiya用户默认头像.png" />
                <p style="margin-left: 8px; color: aliceblue; ">{{ userStoreInfo.userInfo.userName }}</p>
              </div>
              <template #dropdown>
                <el-dropdown-menu style="align-items: center; justify-content: center;">
                  <el-dropdown-item command="profile"
                    style="text-align: center; display: flex; justify-content: center;">
                    个人信息
                  </el-dropdown-item>
                  <el-dropdown-item command="logout"
                    style="text-align: center; display: flex; justify-content: center;">
                    退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

        </div>
      </el-header>

      <!-- 身体 -->
      <el-main class="body" style="min-height:810px ;">
        <!-- 主要内容区 -->
        <el-main class="OverAllCentered_BasedOnFlex" style="flex-direction: column; ">
          <!-- router-view 用于渲染当前路由对应的组件,通过router-link跳转实现 -->
          <router-view></router-view>
          <!-- <MainPage/> -->
        </el-main>
      </el-main>

      <!-- 尾部 -->
      <el-footer class="foot">
        <el-row class="row-bg" justify="space-evenly">
          <el-col :span="6">
            <div class="footer-section">
              <h4>睿雅酒店</h4>
              <p><el-icon>
                  <Location />
                </el-icon> 地址：岭南师范学院</p>
              <p><el-icon>
                  <Phone />
                </el-icon> 电话：666666666</p>
              <p><el-icon>
                  <Message />
                </el-icon> 电子邮件：666666@123.com</p>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="footer-section">
              <h4>入住 / 退房</h4>
              <p>希望您入住愉快，请留意：</p>
              <p><el-icon>
                  <Clock />
                </el-icon> 入住时间：下午2时</p>
              <p><el-icon>
                  <Clock />
                </el-icon> 退房时间：中午12时</p>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="footer-section">
              <h4>支付方式</h4>
              <p>我们接受以下在线支付方式：</p>
              <p><el-icon>
                  <Wallet />
                </el-icon> 微信 / 支付宝</p>
            </div>
          </el-col>
        </el-row>
      </el-footer>
    </el-container>
  </div>


  <el-dialog v-model="showDialog" title="用户登录" width="400px" :close-on-click-modal="false" custom-class="login-dialog"
    @close="handleClose">
    <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" label-width="80px">
      <el-form-item label="账号" prop="userAccountNumber">
        <el-input v-model="loginForm.userAccountNumber" placeholder="请输入账号" clearable prefix-icon="User"
          :validate-event="loginForm.userAccountNumber != null" />
      </el-form-item>
      <el-form-item label="密码" prop="userPassword">
        <el-input v-model="loginForm.userPassword" type="password" placeholder="请输入密码" show-password prefix-icon="Lock"
          :validate-event="loginForm.userPassword != null" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="showDialog = false">取消</el-button>
      <el-button type="primary" @click="handleLogin" :loading="loading">
        登录
      </el-button>
    </template>
  </el-dialog>
</template>



<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Document, Menu as IconMenu, Location, Setting } from '@element-plus/icons-vue'
import { ElMessageBox,ElMessage } from 'element-plus'
import MainPage from './MainPage.vue';
import api from '@/api/index.js';
import { pa } from 'element-plus/es/locale';
import { userStore } from '@/stores/userInfoStore.js';

const userStoreInfo = userStore();

const route = useRoute();
const router = useRouter();
const activeMenuIndex = ref('0');
activeMenuIndex.value = route.meta.activeMenu + ''


const UserLoginToken = ref();

const goToIndex = () => {
  router.push({ 
    path: '/index', 
    // query: { t: Date.now() }  // 添加时间戳强制刷新 [[10]]
  });
}

//#region 登录
const showDialog = ref(false)
const loading = ref(false)
const loginFormRef = ref()



const loginForm = ref({
  userName: '',
  userAccountNumber: '',
  userPassword: ''
})

const loginRules = {
  userAccountNumber: [
    { required: true, message: '请输入账号', trigger: 'change' },
  ],
  userPassword: [
    { required: true, message: '请输入密码', trigger: 'change' },
    { min: 3, max: 18, message: '长度在3到18个字符', trigger: 'blur' }
  ]
}

// 登录
const handleLogin = async () => {
  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) return

    loading.value = true

    // API请求
    await api.UserLogin(loginForm.value).then((res: any) => {
        console.log("用户令牌：",res.data.data)
        localStorage.setItem("ruiYaUserLoginToken",res.data.data)//存令牌
      
    })
    await api.ParseJwt(localStorage.getItem("ruiYaUserLoginToken")).then((res: any) => {

      //拿令牌
      UserLoginToken.value = localStorage.getItem("ruiYaUserLoginToken")
      userStoreInfo.setUserInfo(res.data.data) //res.data.data是用户信息

      showDialog.value = false
      ElMessage.success('登录成功')
    })
  }catch (error: any) {
    ElMessage.error("登录失败，请检查账号或密码");
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  loginFormRef.value.resetFields()
}
//#endregion

// 查看订单前先登录
const orderLogin = () => {
  ElMessage.info('请先登录')
  showDialog.value = true
}

// 处理下拉菜单命令
const handleDropdownCommand = (command: string) => {
  if (command === 'profile') {
    router.push('/Personal'); // 跳转到个人信息页面
  } else if (command === 'logout') {
    handleLogout(); // 执行退出登录逻辑
  }
};

const gotoAllPersonalOrders= ()=>{
    router.push("/allPersonalOrders")
      
   }

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm(
    '您确定要退出登录吗？',
    '退出登录确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 用户点击“确定”后退出登录
      localStorage.removeItem("ruiYaUserLoginToken");
      localStorage.removeItem('activeIndex')
      UserLoginToken.value = null;

      ElMessage.success('已退出登录');
      router.push('/index');
    })
    .catch(() => {
      // 用户点击“取消”时不执行任何操作
      ElMessage.info('取消退出登录');
    });
};

// 监听路由(route.path)变化，更新激活的菜单项索引
watch(() => route.path, () => {
    activeMenuIndex.value = route.meta.activeMenu + '';
});


// 在组件挂载时，确保激活的菜单项索引是最新的
onMounted(async () => {
  activeMenuIndex.value = route.meta.activeMenu + '';
  UserLoginToken.value = localStorage.getItem("ruiYaUserLoginToken");
  // console.log("当前用户信息为:",userStoreInfo.userInfo)
});

</script>


<style scoped>
.OverAllCentered_BasedOnFlex {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.head {
  background: linear-gradient(90deg, #6a5acd, #4682b4); /* 渐变背景 */
  color: #ffffff; /* 文字颜色 */
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 40px;
  height: 60px;
  border-radius: 0 0 10px 10px;
}

.logo h1 {
  cursor: pointer;
  font-family: '楷体', serif;
  font-size: 32px;
  margin: 0;
  color: #ffffff;
}


.actions {
  display: flex;
  align-items: center;
}

.action-btn {
  font-family: 'Arial', sans-serif;
  font-size: 14px;
  color: #ffffff;
  margin-left: 20px;
}

.action-btn .el-icon {
  margin-right: 5px;
  color: #ffffff;
}

.login-btn {
  background-color: #4dc5fc;
  border: none;
  color: #ffffff;
  font-weight: bold;
  padding: 10px 20px;
  border-radius: 20px; /* 圆角按钮 */
}




.body {
    /* background-color:blanchedalmond; */
    width: 80%;
    margin: 0 auto;
    padding: 5px;
}



.foot {
    background-color: #444444;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    height: auto;
    color: #e0e0e0;
    padding: 10px;
}

.footer-section {
    text-align: left;
    line-height: 1.8;
}

.footer-section h4 {
    font-family: '楷体', serif;
    font-size: 20px;
    margin-bottom: 10px;
    color: #ffffff;
}

.footer-section p {
    font-family: 'Arial', sans-serif;
    font-size: 14px;
    color: #c2c2c2;
    margin: 5px 0;
}

.footer-section .el-icon {
    margin-right: 8px;
    color: #66b1ff;
}

@media (max-width: 1024px) {
    .head {
        width: 1024px;
    }

    .body {
        width: 1024px;
    }

    .foot {
        width: 1024px;
    }
}

/* 身体 */
/* .searchbox{
    background-color: aliceblue;
    box-shadow: 0 0 10px;
    border-radius:10px;
    margin-bottom: 3vh;
}

.sideber{
    background-color: aliceblue;
    box-shadow: 0 0 10px;
    border-radius:10px;
    padding: 20px;
    float: left;
}

.main{
    background-color: aliceblue;
    box-shadow: 0 0 10px;
    border-radius:10px;
    padding: 20px;
    float:right;
} */

.login-dialog .el-dialog__body {
  padding: 20px 25px 10px;
}
</style>